import { getItem, setItem } from 'util/storage'

const app = {
  state: {
    sidebar: {
      opened: !+getItem('sidebarStatus')
    },
    tabMode: getItem('tabMode') && getItem('tabMode') === 1,
    visitedViews: (getItem('visitedViews') || [{name: '首页', path: '/home'}]).map(v => {
      v.loaded = false
      return v
    })
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        setItem('sidebarStatus', 1)
      } else {
        setItem('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
    },
    TOGGLE_TAB_MODE: state => {
      if (state.tabMode) {
        setItem('tabMode', 0)
      } else {
        setItem('tabMode', 1)
      }
      state.tabMode = !state.tabMode
    },
    ADD_VISITED_VIEWS: (state, view) => {
      if (state.visitedViews.some(v => v.path === view.path)) {
        return
      }
      state.visitedViews.push({name: view.name, path: view.path})
      setItem('visitedViews', state.visitedViews)
    },
    DEL_VISITED_VIEWS: (state, view) => {
      let index
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          index = i
          break
        }
      }
      state.visitedViews.splice(index, 1)
      setItem('visitedViews', state.visitedViews)
    }
  },
  actions: {
    ToggleSideBar ({commit}) {
      commit('TOGGLE_SIDEBAR')
    },
    ToggleTabMode ({commit}) {
      commit('TOGGLE_TAB_MODE')
    },
    AddVisitedViews ({commit}, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    DelVisitedViews ({commit, state}, view) {
      return new Promise((resolve) => {
        commit('DEL_VISITED_VIEWS', view)
        resolve([...state.visitedViews])
      })
    }
  }
}

export default app
